<?php


namespace App\Game\Core;


use App\Game\Conf\GameProgress;
use App\Game\Conf\SubCmd;
use App\Model\User;
use App\Service\Lock;
use App\Task\GameSyncTask;

class Robot
{

    public static function getRoomRobot($room_no, $account = 0)
    {
        $game_conf = config('game');
        $key = sprintf($game_conf['user_room_robot'], $room_no);
        if ($account) {
            return redis()->hGet($key, (string)$account);
        }
        if (redis()->exists($key)) {
            return redis()->hGetAll($key);
        }
        return [];
    }

    public static function isRobot($room_no, $account)
    {
        $game_conf = config('game');
        $key = sprintf($game_conf['user_room_robot'], $room_no);
        return redis()->hExists($key, (string)$account);
    }


    //添加普通机器人（一次加一个）
    public static function addSingleRobot($room_no)
    {
        $wait = Room::getRoomWait($room_no);
        if (count($wait) == 0) {
            return;
        }
        if (count($wait) > 3) {
            return;
        }
        $robots = self::getRoomRobot($room_no);
        if (count($wait) == count($robots)) {
            return;
        }
        $robot_conf = config('robot');
        $index = array_rand($robot_conf['robots']);
        $account = $robot_conf['robots'][$index];
        while (true) {
            if (!in_array($account, $wait)) {
                break;
            }
        }

        $score = mt_rand(2000, 9587);
        addRoomRobot($room_no, $account, $score);

        Room::addRoomWait($room_no, $account);
        $chair_id = Room::addRoomChair($account, $room_no);

        $wait[] = $account;

        $waitNum = count($wait);
        $master = 0;
        if ($waitNum == 4) {
            $master = rand(1, 4);
        }
        //发送加入消息
        $match_players = [];
        $room_chair_data = Room::getRoomChairs($room_no);
        foreach ($room_chair_data as $acc => $cid) {
            $info = User::userInfo($acc);
            $match_players[] = [
                'account' => $info['account'],
                'nickname' => filterNickname($info['nickname']),
                'avatar' => $info['avatar'],
                'score' => $score,
                'chair_id' => $cid
            ];
        }
        $room_data = ['status' => 'waiting', 'players' => $match_players, 'room_no' => $room_no];
        Message::broadcast($room_no, $room_data, SubCmd::SUB_GAME_WAIT);
        usleep(300);
        //发送准备消息
        $msg = ['status' => 0, 'chair_id' => $chair_id, 'master' => $master];
        Message::broadcast($room_no, $msg, SubCmd::SUB_GAME_PREPARE_RESP);

        //未满员则继续等待
        if ($waitNum < 4) {
            $wait_time = 2 * 1000;
            \Swoole\Timer::after((int)$wait_time, function () use ($room_no) {
                self::addSingleRobot($room_no);
            });
            return;
        }
        //满员
        $robots = self::getRoomRobot($room_no);
        if (count($robots) > 3) {
            Room::cleanRoom($room_no);
            return;
        }
        sleep(2);
        //发牌
        $task = container()->get(GameSyncTask::class);
        $task->assignCards($room_no, $master);
    }

    //添加大奖赛机器人（一次加满）
    public static function addDjsRobots($room_no)
    {
        $robot_conf = config('robot');
        $waiters = Room::getRoomWait($room_no);
        //投放机器人
        $rand_arr = array_rand($robot_conf['robots'], (4 - count($waiters)));
        $rand_no_arr = [];
        foreach ($rand_arr as $v) {
            $waiters[] = $robot_conf['robots'][$v];
            $score = mt_rand(2000, 9587);
            addRoomRobot($room_no, $robot_conf['robots'][$v], $score);
            $rand_no_arr[$robot_conf['robots'][$v]] = $score;
        }
        dd('waiters', $waiters);
        setRoomWaitByArr($room_no, $waiters);

        //设置游戏进度类型为单机
        setGameProgressType($room_no, 1);
        //大奖赛
        Room::updateRoomData($room_no, ['game_type' => 1]);

        $game_conf = config('game');
        //设置座位
        $room_chair_key = sprintf($game_conf['user_room_chair'], $room_no);

        $room_chair_data = [
            $waiters[0] => 1,
            $waiters[1] => 2,
            $waiters[2] => 3,
            $waiters[3] => 4,
        ];

        redis()->set($room_chair_key, json_encode($room_chair_data));// 绑定用户房间号桌位号
        $fd = getFdByAccount($waiters[0]);
        $uinfo = getUserInfoByFd($fd);
        $playerInfo = Djs::getDjsPlayerData($uinfo['account']);
        $match_players[] = [
            'account' => $uinfo['account'],
            'nickname' => filterNickname($uinfo['nickname']),
            'avatar' => $uinfo['avatar'],
            'score' => $uinfo['score'],
            'chair_id' => 1,
            'stage' => $playerInfo['stage'],
            'start_time' => $playerInfo['start_time']
        ];

        foreach ($rand_no_arr as $acc => $score) {
            $info = User::userInfo($acc);
            $chair_id = $room_chair_data[$acc];
            $match_players[] = [
                'account' => $info['account'],
                'nickname' => filterNickname($info['nickname']),
                'avatar' => $info['avatar'],
                'score' => $score,
                'chair_id' => $chair_id,
                'stage' => $playerInfo['stage'],
                'start_time' => $playerInfo['start_time']
            ];
        }
        dd('match_players', $match_players);
        return $match_players;
    }

    //添加大奖赛机器人（一次加一个）
    public static function addSingleDjsRobot($room_no)
    {
        $key = 'join_grand_match_' . $room_no;
        while (true) {
            if (!Lock::lock($key, 2)) {
                $ttl = redis()->ttl($key);
                if ($ttl < 0) {
                    redis()->expire($key, 2);
                }
                sleep(1);
                continue;
            }
            ddTitle('add djs robot room_no: ' . $room_no);
            $wait = Room::getRoomWait($room_no);
            if (count($wait) == 0) {
                Room::cleanRoom($room_no);
                break;
            }
            if (count($wait) > 3) {
                break;
            }
            $robots = self::getRoomRobot($room_no);
            if (count($wait) == count($robots)) {
                break;
            }
            $robot_conf = config('robot');
            $index = array_rand($robot_conf['robots']);
            $account = $robot_conf['robots'][$index];
            if (in_array($account, $wait)) {
                continue;
            }
            $score = mt_rand(2000, 9587);
            addRoomRobot($room_no, $account, $score);

            Room::addRoomWait($room_no, $account);
            Room::addRoomChair($account, $room_no);


            $wait[] = $account;
            //未满员则继续等待
            if (count($wait) < 4) {
                $robot_conf = config('robot');
                $wait_time = $robot_conf['djs_wait_join_timer'] * 1000;
                \Swoole\Timer::after((int)$wait_time, function () use ($room_no) {
                    self::addSingleDjsRobot($room_no);
                });
                break;
            }
            $robots = self::getRoomRobot($room_no);
            if (count($robots) > 3) {
                Room::cleanRoom($room_no);
                break;
            }
            //满员
            $players = Djs::initMatchData($room_no);
            $msg = [
                'status' => 'success',
                'room_no' => $room_no,
                'players' => $players
            ];
            Message::broadcast($room_no, $msg, SubCmd::GAME_QUICK_MATCH, 1);
            Djs::removeWaitRoom($room_no);
            setGameProgress($room_no, GameProgress::GAME_PREPARE);
        }
    }

}